package org.gvp.generator.db;

import org.gvp.generator.log.LogFactory;
import org.gvp.generator.log.Logger;
import org.gvp.generator.props.DatabaseProps;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectHandler {
    private final Logger log = LogFactory.getLogger(this.getClass());
    private DatabaseProps database;
    public ConnectHandler(DatabaseProps database) {
        this.database=database;
    }

    /**
     * 获取数据库连接对象
     */
    public Connection getConnection() {
        try {
            Class.forName(this.database.getDriver());
        } catch (ClassNotFoundException e) {
            log.error("数据库驱动加载失败");
            throw new RuntimeException("数据库驱动加载失败");
        }
        try {
            return DriverManager.getConnection(database.getUrl(), database.getUsername(), database.getPassword());
        } catch (SQLException e) {
            log.error("数据库连接失败");
            throw new RuntimeException("数据库连接失败");
        }
    }
}
